import json

import requests
from transformers import pipeline


def generate_response(prompt):
    """调用本地Ollama模型生成响应"""
    try:
        data = {
            'model': 'deepseek-r1:1.5b',
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            "options": {
                "num_ctx": 512,
                "raw": True  # 跳过思考过程
            },
            "stream": False  # 获取完整响应
        }
        # print("开始")
        response = requests.post(
            "http://127.0.0.1:11434/api/chat",
            json=data
        )

        if response.status_code == 200:
            response_data = response.json()
            # 直接从message中提取content
            return response_data.get('message', {}).get('content', '未收到有效回复')
        else:
            print(f"请求失败，状态码: {response.status_code}")
            print("错误详情:", response.text)
            return "当前服务暂时不可用，请稍后再试"

    except requests.exceptions.RequestException as e:
        print(f"请求异常: {str(e)}")
        return "网络连接出现问题，请检查服务是否运行"
    except json.JSONDecodeError:
        print("响应解析失败，原始响应")
        return "服务响应格式错误"
    except Exception as e:
        print(f"未知错误: {str(e)}")
        return "生成回复时出现错误"


# class AIClient:
#     # def analyze_emotion(self, text):
#     #     """情感分析"""
#     #     result = self.emotion_analyzer(text)[0]
#     #     return {
#     #         "label": result["label"],
#     #         "score": result["score"]
#     #     }
